<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">



















  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext">
  






<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/favicon.ico?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"hide","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="keywords" content="正则表达式">
<meta property="og:type" content="article">
<meta property="og:title" content="正则表达式学习">
<meta property="og:url" content="https://www.dudefu.tk/正则表达式学习.html">
<meta property="og:site_name" content="The Future">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx9asrcuj30rg0fuq5u.jpg">
<meta property="og:image" content="https://pic2.zhimg.com/50/v2-4cb7311c65df765b3b0af137e53375eb_hd.jpg?source=1940ef5c">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8s4dyij30h008tgm5.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8owvb1j30h007p0t3.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8n0nlpj30h007p0t3.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8gjeffj30h204hq34.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8e2aizj30h204hq34.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx87gv3vj30gz04fjrm.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx85mxkrj30gz04fjrm.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx80kguhj30gy039aa5.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx82sg21j30gy039aa5.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx7t2lygj30h206mq3g.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx7r9n6wj30h206mq3g.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx7e070dj30h307twf5.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx7i6xktj30h307twf5.jpg">
<meta property="og:updated_time" content="2021-01-18T08:45:58.156Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="正则表达式学习">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx9asrcuj30rg0fuq5u.jpg">





  
  
  <link rel="canonical" href="https://www.dudefu.tk/正则表达式学习">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>正则表达式学习 | The Future</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">The Future</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Stay hungry,stay foolish.</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档<span class="badge">125</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    
      
    

    <a href="/categories" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类<span class="badge">15</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    
      
    

    <a href="/tags" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签<span class="badge">63</span></a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-something">

    
    
    
      
    

    
      
    

    <a href="/something" rel="section"><i class="menu-item-icon fa fa-fw fa-paper-plane"></i> <br>干货</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    
      
    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  
    <div class="reading-progress-bar"></div>
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.dudefu.tk/正则表达式学习.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Daniel X">
      <meta itemprop="description" content="專注于大数据技術，分享干货">
      <meta itemprop="image" content="https://hexoblog-1254111960.cos.ap-guangzhou.myqcloud.com/HexoBlog-tou.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="The Future">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">正则表达式学习

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2021-01-18 16:17:30 / 修改时间：16:45:58" itemprop="dateCreated datePublished" datetime="2021-01-18T16:17:30+08:00">2021-01-18</time>
            

            
              

              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/正则表达式学习.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/正则表达式学习.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/正则表达式学习.html" class="leancloud_visitors" data-flag-title="正则表达式学习">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx9asrcuj30rg0fuq5u.jpg" alt="img"></p>
<a id="more"></a>
<p>正则表达式在几乎所有语言中都可以使用，无论是前端的JavaScript、还是后端的Java、c#。他们都提供相应的接口/函数支持正则表达式。</p>
<p>但很神奇的是：<strong><em>无论你大学选择哪一门计算机语言，都没有关于正则表达式的课程给你修，在你学会正则之前，你只能看着那些正则大师们，写了一串外星文似的字符串，替代了你用一大篇幅的if else代码来做一些数据校验</em></strong>。</p>
<p>既然喜欢，那就动手学呗，可当你百度出一一堆相关资料时，你发现无一不例外的枯燥至极，难以学习。</p>
<p>本文旨在用最通俗的语言讲述最枯燥的基本知识！</p>
<h2 id="正则基础知识点："><a href="#正则基础知识点：" class="headerlink" title="正则基础知识点："></a><strong>正则基础知识点：</strong></h2><h3 id="1-元字符"><a href="#1-元字符" class="headerlink" title="1.元字符"></a><strong>1.元字符</strong></h3><p>万物皆有缘，正则也是如此，元字符是构造正则表达式的一种基本元素。<br>我们先来记几个常用的元字符：</p>
<p><img src="https://pic2.zhimg.com/50/v2-4cb7311c65df765b3b0af137e53375eb_hd.jpg?source=1940ef5c" alt="img"><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8s4dyij30h008tgm5.jpg" alt="img"></p>
<p>有了元字符之后，我们就可以利用这些元字符来写一些简单的正则表达式了，<br>比如：</p>
<ol>
<li>匹配有abc开头的字符串：</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   \babc或者^abc</span><br></pre></td></tr></table></figure>
<p>\2. 匹配8位数字的QQ号码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^\d\d\d\d\d\d\d\d$</span><br></pre></td></tr></table></figure>
<p>\3. 匹配1开头11位数字的手机号码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^<span class="number">1</span>\d\d\d\d\d\d\d\d\d\d$</span><br></pre></td></tr></table></figure>
<h3 id="2-重复限定符"><a href="#2-重复限定符" class="headerlink" title="2. 重复限定符"></a><strong>2. 重复限定符</strong></h3><p>有了元字符就可以写不少的正则表达式了，但细心的你们可能会发现：别人写的正则简洁明了，而不理君写的正则一堆乱七八糟而且重复的元字符组成的。正则没提供办法处理这些重复的元字符吗？</p>
<p>答案是有的！<br>为了处理这些重复问题，正则表达式中一些重复限定符，把重复部分用合适的限定符替代，下面我们来看一些限定符：</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8owvb1j30h007p0t3.jpg" alt="img"><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8n0nlpj30h007p0t3.jpg" alt="img"></p>
<p>有了这些限定符之后，我们就可以对之前的正则表达式进行改造了，比如：</p>
<p>\1. 匹配8位数字的QQ号码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^\d&#123;<span class="number">8</span>&#125;$</span><br></pre></td></tr></table></figure>
<p>\2. 匹配1开头11位数字的手机号码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^<span class="number">1</span>\d&#123;<span class="number">10</span>&#125;$</span><br></pre></td></tr></table></figure>
<p>\3. 匹配银行卡号是14~18位的数字：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^\d&#123;<span class="number">14</span>,<span class="number">18</span>&#125;$</span><br></pre></td></tr></table></figure>
<p>\4. 匹配以a开头的，0个或多个b结尾的字符串</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^ab*$</span><br></pre></td></tr></table></figure>
<h3 id="3-分组"><a href="#3-分组" class="headerlink" title="3. 分组"></a><strong>3. 分组</strong></h3><p>从上面的例子（4）中看到，<em>限定符是作用在与他左边最近的一个字符，那么问题来了，如果我想要ab同时被</em>限定那怎么办呢？</p>
<blockquote>
<p>正则表达式中用小括号()来做分组，也就是括号中的内容作为一个整体。</p>
</blockquote>
<p>因此当我们要匹配多个ab时，我们可以这样<br>如：匹配字符串中包含0到多个ab开头：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^(ab)*</span><br></pre></td></tr></table></figure>
<h3 id="4-转义"><a href="#4-转义" class="headerlink" title="4. 转义"></a><strong>4. 转义</strong></h3><p>我们看到正则表达式用小括号来做分组，那么问题来了：</p>
<blockquote>
<p>如果要匹配的字符串中本身就包含小括号，那是不是冲突？应该怎么办？</p>
</blockquote>
<p>针对这种情况，正则提供了转义的方式，也就是要把这些元字符、限定符或者关键字转义成普通的字符，做法很简答，就是在要转义的字符前面加个斜杠，也就是\即可。<br>如：要匹配以(ab)开头：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^(\(ab\))*</span><br></pre></td></tr></table></figure>
<h3 id="5-条件或"><a href="#5-条件或" class="headerlink" title="5. 条件或"></a><strong>5. 条件或</strong></h3><p>回到我们刚才的手机号匹配，我们都知道：国内号码都来自三大网，它们都有属于自己的号段，比如联通有130/131/132/155/156/185/186/145/176等号段，假如让我们匹配一个联通的号码，那按照我们目前所学到的正则，应该无从下手的，因为这里包含了一些并列的条件，也就是“或”，那么在正则中是如何表示“或”的呢？</p>
<blockquote>
<p>正则用符号 | 来表示或，也叫做分支条件，当满足正则里的分支条件的任何一种条件时，都会当成是匹配成功。</p>
</blockquote>
<p>那么我们就可以用或条件来处理这个问题</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^(<span class="number">130</span>|<span class="number">131</span>|<span class="number">132</span>|<span class="number">155</span>|<span class="number">156</span>|<span class="number">185</span>|<span class="number">186</span>|<span class="number">145</span>|<span class="number">176</span>)\d&#123;<span class="number">8</span>&#125;$</span><br></pre></td></tr></table></figure>
<h3 id="6-区间"><a href="#6-区间" class="headerlink" title="6. 区间"></a><strong>6. 区间</strong></h3><p>看到上面的例子，是不是看到有什么规律？是不是还有一种想要简化的冲动？<br>实际是有的</p>
<blockquote>
<p>正则提供一个元字符中括号 [] 来表示区间条件。</p>
</blockquote>
<ol>
<li>限定0到9 可以写成[0-9]</li>
<li>限定A-Z 写成[A-Z]</li>
<li>限定某些数字 [165]</li>
</ol>
<p>那上面的正则我们还改成这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   ^((<span class="number">13</span>[<span class="number">0</span>-<span class="number">2</span>])|(<span class="number">15</span>[<span class="number">56</span>])|(<span class="number">18</span>[<span class="number">5</span>-<span class="number">6</span>])|<span class="number">145</span>|<span class="number">176</span>)\d&#123;<span class="number">8</span>&#125;$</span><br></pre></td></tr></table></figure>
<p>好了，正则表达式的基本用法就讲到这里了，其实它还有非常多的知识点以及元字符，我们在此只列举了部分元字符和语法来讲，旨在给那些不懂正则或者想学正则但有看不下去文档的人做一个快速入门级的教程，看完本教程，即使你不能写出高大上的正则，至少也能写一些简单的正则或者看得懂别人写的正则了。</p>
<h2 id="正则进阶知识点："><a href="#正则进阶知识点：" class="headerlink" title="正则进阶知识点："></a><strong>正则进阶知识点：</strong></h2><h3 id="1-零宽断言"><a href="#1-零宽断言" class="headerlink" title="1. 零宽断言"></a><strong>1. 零宽断言</strong></h3><blockquote>
<p>无论是零宽还是断言，听起来都古古怪怪的，<br>那先解释一下这两个词。</p>
</blockquote>
<ol>
<li>断言：俗话的断言就是“我断定什么什么”，而正则中的断言，就是说正则可以指明在指定的内容的前面或后面会出现满足指定规则的内容，<br>意思正则也可以像人类那样断定什么什么，比如”ss1aa2bb3”,正则可以用断言找出aa2前面有bb3，也可以找出aa2后面有ss1.</li>
<li>零宽：就是没有宽度，在正则中，断言只是匹配位置，不占字符，也就是说，匹配结果里是不会返回断言本身。</li>
</ol>
<p>意思是讲明白了，那他有什么用呢？<br>我们来举个栗子：<br>假设我们要用爬虫抓取csdn里的文章阅读量。通过查看源代码可以看到文章阅读量这个内容是这样的结构</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1   &quot;&lt;span class=&quot;read-count&quot;&gt;阅读数：641&lt;/span&gt;&quot;</span><br></pre></td></tr></table></figure>
<p>其中也就‘641’这个是变量，也就是说不同文章不同的值，当我们拿到这个字符串时，需要获得这里边的‘641’有很多种办法，但如果正则应该怎么匹配呢？</p>
<p>下面先来讲几种类型的断言：</p>
<ol>
<li>正向先行断言（正前瞻）：</li>
</ol>
<ul>
<li>语法：（?=pattern）</li>
<li>作用：匹配pattern表达式的前面内容，不返回本身。</li>
</ul>
<p>这样子说，还是一脸懵逼，好吧，回归刚才那个栗子，要取到阅读量，在正则表达式中就意味着要能匹配到‘’前面的数字内容<br>按照上所说的正向先行断言可以匹配表达式前面的内容，那意思就是:(?=) 就可以匹配到前面的内容了。<br>匹配什么内容呢？如果要所有内容那就是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"> <span class="number">1</span>   String reg=<span class="string">".+(?=&lt;/span&gt;)"</span>;</span><br><span class="line"> <span class="number">2</span></span><br><span class="line"> <span class="number">3</span>   String test = <span class="string">"&lt;span class=\"read-count\"&gt;阅读数：641&lt;/span&gt;"</span>;</span><br><span class="line"> <span class="number">4</span>   Pattern pattern = Pattern.compile(reg);</span><br><span class="line"> <span class="number">5</span>   Matcher mc=    pattern.matcher(test);</span><br><span class="line"> <span class="number">6</span>   <span class="keyword">while</span>(mc.find())&#123;</span><br><span class="line"> <span class="number">7</span>    System.out.println(<span class="string">"匹配结果："</span>)</span><br><span class="line"> <span class="number">8</span>    System.out.println(mc.group());</span><br><span class="line"> <span class="number">9</span>   &#125;</span><br><span class="line"><span class="number">10</span></span><br><span class="line"><span class="number">11</span>   <span class="comment">//匹配结果：</span></span><br><span class="line"><span class="number">12</span>   <span class="comment">//&lt;span class="read-count"&gt;阅读数：641</span></span><br></pre></td></tr></table></figure>
<p>可是老哥我们要的只是前面的数字呀，那也简单咯，匹配数字 \d,那可以改成：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   String reg=<span class="string">"\\d+(?=&lt;/span&gt;)"</span>;</span><br><span class="line"><span class="number">2</span>   String test = <span class="string">"&lt;span class=\"read-count\"&gt;阅读数：641&lt;/span&gt;"</span>;</span><br><span class="line"><span class="number">3</span>   Pattern pattern = Pattern.compile(reg);</span><br><span class="line"><span class="number">4</span>   Matcher mc=    pattern.matcher(test);</span><br><span class="line"><span class="number">5</span>   <span class="keyword">while</span>(mc.find())&#123;</span><br><span class="line"><span class="number">6</span>     System.out.println(mc.group());</span><br><span class="line"><span class="number">7</span>   &#125;</span><br><span class="line"><span class="number">8</span>   <span class="comment">//匹配结果：</span></span><br><span class="line"><span class="number">9</span>   <span class="comment">//641</span></span><br></pre></td></tr></table></figure>
<p>大功告成！</p>
<p>\2. 正向后行断言（正后顾）:</p>
<ul>
<li>语法：（?&lt;=pattern）</li>
<li>作用：匹配pattern表达式的后面的内容，不返回本身。</li>
</ul>
<p>有先行就有后行，先行是匹配前面的内容，那后行就是匹配后面的内容啦。<br>上面的栗子，我们也可以用后行断言来处理.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"> <span class="number">1</span>   <span class="comment">//(?&lt;=&lt;span class="read-count"&gt;阅读数：)\d+</span></span><br><span class="line"> <span class="number">2</span>   String reg=<span class="string">"(?&lt;=&lt;span class=\"read-count\"&gt;阅读数：)\\d+"</span>;</span><br><span class="line"> <span class="number">3</span></span><br><span class="line"> <span class="number">4</span>   String test = <span class="string">"&lt;span class=\"read-count\"&gt;阅读数：641&lt;/span&gt;"</span>;</span><br><span class="line"> <span class="number">5</span>   Pattern pattern = Pattern.compile(reg);</span><br><span class="line"> <span class="number">6</span>   Matcher mc=    pattern.matcher(test);</span><br><span class="line"> <span class="number">7</span>        <span class="keyword">while</span>(mc.find())&#123;</span><br><span class="line"> <span class="number">8</span>          System.out.println(mc.group());</span><br><span class="line"> <span class="number">9</span>        &#125;</span><br><span class="line"><span class="number">10</span>   <span class="comment">//匹配结果：</span></span><br><span class="line"><span class="number">11</span>   <span class="comment">//641</span></span><br></pre></td></tr></table></figure>
<p>就这么简单。</p>
<p>\3. 负向先行断言（负前瞻）</p>
<ul>
<li>语法：(?!pattern)</li>
<li>作用：匹配非pattern表达式的前面内容，不返回本身。</li>
</ul>
<p>有正向也有负向，负向在这里其实就是非的意思。<br>举个栗子：比如有一句 “我爱祖国，我是祖国的花朵”<br>现在要找到不是’的花朵’前面的祖国<br>用正则就可以这样写：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   祖国(?!的花朵)</span><br></pre></td></tr></table></figure>
<p>\4. 负向后行断言（负后顾）</p>
<ul>
<li>语法：(?&lt;!pattern)</li>
<li>作用：匹配非pattern表达式的后面内容，不返回本身。</li>
</ul>
<h3 id="2-捕获和非捕获"><a href="#2-捕获和非捕获" class="headerlink" title="2. 捕获和非捕获"></a><strong>2. 捕获和非捕获</strong></h3><p>单纯说到捕获，他的意思是匹配表达式，但捕获通常和分组联系在一起，也就是“捕获组”</p>
<blockquote>
<p>捕获组：匹配子表达式的内容，把匹配结果保存到内存中中数字编号或显示命名的组里，以深度优先进行编号，之后可以通过序号或名称来使用这些匹配结果。</p>
</blockquote>
<p>而根据命名方式的不同，又可以分为两种组：</p>
<p>\1. 数字编号捕获组：<br>语法：(exp)<br>解释：从表达式左侧开始，每出现一个左括号和它对应的右括号之间的内容为一个分组，在分组中，第0组为整个表达式，第一组开始为分组。<br>比如固定电话的：020-85653333<br>他的正则表达式为：(0\d{2})-(\d{8})<br>按照左括号的顺序，这个表达式有如下分组：</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8gjeffj30h204hq34.jpg" alt="img"><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx8e2aizj30h204hq34.jpg" alt="img"></p>
<p>我们用Java来验证一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"> <span class="number">1</span>   String test = <span class="string">"020-85653333"</span>;</span><br><span class="line"> <span class="number">2</span>        String reg=<span class="string">"(0\\d&#123;2&#125;)-(\\d&#123;8&#125;)"</span>;</span><br><span class="line"> <span class="number">3</span>        Pattern pattern = Pattern.compile(reg);</span><br><span class="line"> <span class="number">4</span>        Matcher mc= pattern.matcher(test);</span><br><span class="line"> <span class="number">5</span>        <span class="keyword">if</span>(mc.find())&#123;</span><br><span class="line"> <span class="number">6</span>          System.out.println(<span class="string">"分组的个数有："</span>+mc.groupCount());</span><br><span class="line"> <span class="number">7</span>            <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=mc.groupCount();i++)&#123;</span><br><span class="line"> <span class="number">8</span>                System.out.println(<span class="string">"第"</span>+i+<span class="string">"个分组为："</span>+mc.group(i));</span><br><span class="line"> <span class="number">9</span>            &#125;</span><br><span class="line"><span class="number">10</span>        &#125;</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   分组的个数有：<span class="number">2</span></span><br><span class="line"><span class="number">2</span>   第<span class="number">0</span>个分组为：<span class="number">020</span>-<span class="number">85653333</span></span><br><span class="line"><span class="number">3</span>   第<span class="number">1</span>个分组为：<span class="number">020</span></span><br><span class="line"><span class="number">4</span>   第<span class="number">2</span>个分组为：<span class="number">85653333</span></span><br></pre></td></tr></table></figure>
<p>可见，分组个数是2，但是因为第0个为整个表达式本身，因此也一起输出了。</p>
<p>\2. 命名编号捕获组：<br>语法：(?<name>exp)<br>解释：分组的命名由表达式中的name指定<br>比如区号也可以这样写:(?<quhao>\0\d{2})-(?<haoma>\d{8})<br>按照左括号的顺序，这个表达式有如下分组：</haoma></quhao></name></p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx87gv3vj30gz04fjrm.jpg" alt="img"><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx85mxkrj30gz04fjrm.jpg" alt="img"></p>
<p>用代码来验证一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   String test = <span class="string">"020-85653333"</span>;</span><br><span class="line"><span class="number">2</span>        String reg=<span class="string">"(?&lt;quhao&gt;0\\d&#123;2&#125;)-(?&lt;haoma&gt;\\d&#123;8&#125;)"</span>;</span><br><span class="line"><span class="number">3</span>        Pattern pattern = Pattern.compile(reg);</span><br><span class="line"><span class="number">4</span>        Matcher mc= pattern.matcher(test);</span><br><span class="line"><span class="number">5</span>        <span class="keyword">if</span>(mc.find())&#123;</span><br><span class="line"><span class="number">6</span>            System.out.println(<span class="string">"分组的个数有："</span>+mc.groupCount());</span><br><span class="line"><span class="number">7</span>            System.out.println(mc.group(<span class="string">"quhao"</span>));</span><br><span class="line"><span class="number">8</span>            System.out.println(mc.group(<span class="string">"haoma"</span>));</span><br><span class="line"><span class="number">9</span>        &#125;</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   分组的个数有：<span class="number">2</span></span><br><span class="line"><span class="number">2</span>   分组名称为:quhao,匹配内容为：<span class="number">020</span></span><br><span class="line"><span class="number">3</span>   分组名称为:haoma,匹配内容为：<span class="number">85653333</span></span><br></pre></td></tr></table></figure>
<p>\3. 非捕获组：<br>语法：(?:exp)<br>解释：和捕获组刚好相反，它用来标识那些不需要捕获的分组，说的通俗一点，就是你可以根据需要去保存你的分组。</p>
<p>比如上面的正则表达式，程序不需要用到第一个分组，那就可以这样写：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   (?:\<span class="number">0</span>\d&#123;<span class="number">2</span>&#125;)-(\d&#123;<span class="number">8</span>&#125;)</span><br></pre></td></tr></table></figure>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx80kguhj30gy039aa5.jpg" alt="img"><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx82sg21j30gy039aa5.jpg" alt="img"></p>
<p>验证一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"> <span class="number">1</span>   String test = <span class="string">"020-85653333"</span>;</span><br><span class="line"> <span class="number">2</span>        String reg=<span class="string">"(?:0\\d&#123;2&#125;)-(\\d&#123;8&#125;)"</span>;</span><br><span class="line"> <span class="number">3</span>        Pattern pattern = Pattern.compile(reg);</span><br><span class="line"> <span class="number">4</span>        Matcher mc= pattern.matcher(test);</span><br><span class="line"> <span class="number">5</span>        <span class="keyword">if</span>(mc.find())&#123;</span><br><span class="line"> <span class="number">6</span>                System.out.println(<span class="string">"分组的个数有："</span>+mc.groupCount());</span><br><span class="line"> <span class="number">7</span>                <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=mc.groupCount();i++)&#123;</span><br><span class="line"> <span class="number">8</span>                    System.out.println(<span class="string">"第"</span>+i+<span class="string">"个分组为："</span>+mc.group(i));</span><br><span class="line"> <span class="number">9</span>                &#125;</span><br><span class="line"><span class="number">10</span>        &#125;</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   分组的个数有：<span class="number">1</span></span><br><span class="line"><span class="number">2</span>   第<span class="number">0</span>个分组为：<span class="number">020</span>-<span class="number">85653333</span></span><br><span class="line"><span class="number">3</span>   第<span class="number">1</span>个分组为：<span class="number">85653333</span></span><br></pre></td></tr></table></figure>
<h3 id="3-反向引用"><a href="#3-反向引用" class="headerlink" title="3. 反向引用"></a><strong>3. 反向引用</strong></h3><p>上面讲到捕获，我们知道：<strong><em>捕获会返回一个捕获组，这个分组是保存在内存中，不仅可以在正则表达式外部通过程序进行引用，也可以在正则表达式内部进行引用，这种引用方式就是反向引用</em></strong>。</p>
<p>根据捕获组的命名规则，反向引用可分为：</p>
<ol>
<li>数字编号组反向引用：\k<br>或\number</li>
<li>命名编号组反向引用：\k<br>或者\’name’</li>
</ol>
<p>好了 讲完了，懂吗？不懂！！！<br>可能连前面讲的捕获有什么用都还不懂吧？<br>其实只是看完捕获不懂不会用是很正常的！<br>因为捕获组通常是和反向引用一起使用的</p>
<p>上面说到捕获组是匹配子表达式的内容按序号或者命名保存起来以便使用<br>注意两个字眼：“内容” 和 “使用”<br>这里所说的“内容”，是匹配结果，而不是子表达式本身，强调这个有什么用？嗯，先记住<br>那这里所说的“使用”是怎样使用呢？</p>
<p>因为它的作用主要是用来查找一些重复的内容或者做替换指定字符。</p>
<p>还是举栗子吧：<br>比如要查找一串字母”aabbbbgbddesddfiid”里成对的字母<br>如果按照我们之前学到的正则，什么区间啊限定啊断言啊可能是办不到的，<br>现在我们先用程序思维理一下思路：</p>
<ul>
<li>1）匹配到一个字母</li>
<li>2）匹配第下一个字母，检查是否和上一个字母是否一样</li>
<li>3）如果一样，则匹配成功，否则失败</li>
</ul>
<p>这里的思路2中匹配下一个字母时，需要用到上一个字母，那怎么记住上一个字母呢？？？<br>这下子捕获就有用处啦，我们可以利用捕获把上一个匹配成功的内容用来作为本次匹配的条件<br>好了，有思路就要实践<br>首先匹配一个字母：\w<br>我们需要做成分组才能捕获，因此写成这样：(\w)</p>
<p>那这个表达式就有一个捕获组：（\w）<br>然后我们要用这个捕获组作为条件，那就可以：(\w)\1<br>这样就大功告成了<br>可能有人不明白了，\1是什么意思呢？<br>还记得捕获组有两种命名方式吗，<strong>一种是是根据捕获分组顺序命名，一种是自定义命名来作为捕获组的命名</strong><br><strong><em>在默认情况下都是以数字来命名，而且数字命名的顺序是从1开始的\</em></strong><br>因此要引用第一个捕获组，根据反向引用的数字命名规则 就需要 \k<1>或者\1<br>当然，通常都是是后者。<br>我们来测试一下：</1></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   String test = <span class="string">"aabbbbgbddesddfiid"</span>;</span><br><span class="line"><span class="number">2</span>        Pattern pattern = Pattern.compile(<span class="string">"(\\w)\\1"</span>);</span><br><span class="line"><span class="number">3</span>        Matcher mc= pattern.matcher(test);</span><br><span class="line"><span class="number">4</span>        <span class="keyword">while</span>(mc.find())&#123;</span><br><span class="line"><span class="number">5</span>            System.out.println(mc.group());</span><br><span class="line"><span class="number">6</span></span><br><span class="line"><span class="number">7</span>        &#125;</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   aa</span><br><span class="line"><span class="number">2</span>   bb</span><br><span class="line"><span class="number">3</span>   bb</span><br><span class="line"><span class="number">4</span>   dd</span><br><span class="line"><span class="number">5</span>   dd</span><br><span class="line"><span class="number">6</span>   ii</span><br></pre></td></tr></table></figure>
<p>嗯，这就是我们想要的了。</p>
<p>在举个替换的例子，假如想要把字符串中abc换成a</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   String test = <span class="string">"abcbbabcbcgbddesddfiid"</span>;</span><br><span class="line"><span class="number">2</span>   String reg=<span class="string">"(a)(b)c"</span>;</span><br><span class="line"><span class="number">3</span>   System.out.println(test.replaceAll(reg, <span class="string">"$1"</span>));;</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   abbabcgbddesddfiid</span><br></pre></td></tr></table></figure>
<h3 id="4-贪婪和非贪婪"><a href="#4-贪婪和非贪婪" class="headerlink" title="4. 贪婪和非贪婪"></a><strong>4. 贪婪和非贪婪</strong></h3><p><strong>1.贪婪</strong></p>
<p>我们都知道，贪婪就是不满足，尽可能多的要。<br>在正则中，贪婪也是差不多的意思:</p>
<blockquote>
<p>贪婪匹配：当正则表达式中包含能接受重复的限定符时，通常的行为是（在使整个表达式能得到匹配的前提下）匹配尽可能多的字符，这匹配方式叫做贪婪匹配。<br>特性：一次性读入整个字符串进行匹配，每当不匹配就舍弃最右边一个字符，继续匹配，依次匹配和舍弃（这种匹配-舍弃的方式也叫做回溯），直到匹配成功或者把整个字符串舍弃完为止，因此它是一种最大化的数据返回，能多不会少。</p>
</blockquote>
<p>前面我们讲过重复限定符，其实这些限定符就是贪婪量词，比如表达式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   \d&#123;<span class="number">3</span>,<span class="number">6</span>&#125;</span><br></pre></td></tr></table></figure>
<p>用来匹配3到6位数字，在这种情况下，它是一种贪婪模式的匹配，也就是假如字符串里有6个个数字可以匹配，那它就是全部匹配到。<br>如</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   String reg=<span class="string">"\\d&#123;3,6&#125;"</span>;        </span><br><span class="line"><span class="number">2</span>   String test=<span class="string">"61762828 176 2991 871"</span>;</span><br><span class="line"><span class="number">3</span>   System.out.println(<span class="string">"文本："</span>+test);</span><br><span class="line"><span class="number">4</span>   System.out.println(<span class="string">"贪婪模式："</span>+reg);</span><br><span class="line"><span class="number">5</span>   Pattern p1 =Pattern.compile(reg);</span><br><span class="line"><span class="number">6</span>   Matcher m1 = p1.matcher(test);</span><br><span class="line"><span class="number">7</span>    <span class="keyword">while</span>(m1.find())&#123;</span><br><span class="line"><span class="number">8</span>      System.out.println(<span class="string">"匹配结果："</span>+m1.group(<span class="number">0</span>));</span><br><span class="line"><span class="number">9</span>   &#125;</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   文本：<span class="number">61762828</span> <span class="number">176</span> <span class="number">2991</span> <span class="number">44</span> <span class="number">871</span></span><br><span class="line"><span class="number">2</span>   贪婪模式：\d&#123;<span class="number">3</span>,<span class="number">6</span>&#125;</span><br><span class="line"><span class="number">3</span>   匹配结果：<span class="number">617628</span></span><br><span class="line"><span class="number">4</span>   匹配结果：<span class="number">176</span></span><br><span class="line"><span class="number">5</span>   匹配结果：<span class="number">2991</span></span><br><span class="line"><span class="number">6</span>   匹配结果：<span class="number">871</span></span><br></pre></td></tr></table></figure>
<p>由结果可见：本来字符串中的“61762828”这一段，其实只需要出现3个（617）就已经匹配成功了的，但是他并不满足，而是匹配到了最大能匹配的字符，也就是6个。<br>一个量词就如此贪婪了，<br>那有人会问，如果多个贪婪量词凑在一起，那他们是如何支配自己的匹配权的呢？</p>
<blockquote>
<p>是这样的，多个贪婪在一起时，如果字符串能满足他们各自最大程度的匹配时，就互不干扰，但如果不能满足时，会根据深度优先原则，也就是从左到右的每一个贪婪量词，优先最大数量的满足，剩余再分配下一个量词匹配。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   String reg=<span class="string">"(\\d&#123;1,2&#125;)(\\d&#123;3,4&#125;)"</span>;        </span><br><span class="line"><span class="number">2</span>   String test=<span class="string">"61762828 176 2991 87321"</span>;</span><br><span class="line"><span class="number">3</span>   System.out.println(<span class="string">"文本："</span>+test);</span><br><span class="line"><span class="number">4</span>   System.out.println(<span class="string">"贪婪模式："</span>+reg);</span><br><span class="line"><span class="number">5</span>   Pattern p1 =Pattern.compile(reg);</span><br><span class="line"><span class="number">6</span>   Matcher m1 = p1.matcher(test);</span><br><span class="line"><span class="number">7</span>    <span class="keyword">while</span>(m1.find())&#123;</span><br><span class="line"><span class="number">8</span>      System.out.println(<span class="string">"匹配结果："</span>+m1.group(<span class="number">0</span>));</span><br><span class="line"><span class="number">9</span>     &#125;</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   文本：<span class="number">61762828</span> <span class="number">176</span> <span class="number">2991</span> <span class="number">87321</span></span><br><span class="line"><span class="number">2</span>   贪婪模式：(\d&#123;<span class="number">1</span>,<span class="number">2</span>&#125;)(\d&#123;<span class="number">3</span>,<span class="number">4</span>&#125;)</span><br><span class="line"><span class="number">3</span>   匹配结果：<span class="number">617628</span></span><br><span class="line"><span class="number">4</span>   匹配结果：<span class="number">2991</span></span><br><span class="line"><span class="number">5</span>   匹配结果：<span class="number">87321</span></span><br></pre></td></tr></table></figure>
<ol>
<li>“617628” 是前面的\d{1,2}匹配出了61，后面的匹配出了7628</li>
<li>“2991” 是前面的\d{1,2}匹配出了29 ，后面的匹配出了91</li>
<li>“87321”是前面的\d{1,2}匹配出了87，后面的匹配出了321</li>
</ol>
<p><strong>2. 懒惰（非贪婪）</strong></p>
<blockquote>
<p>懒惰匹配：当正则表达式中包含能接受重复的限定符时，通常的行为是（在使整个表达式能得到匹配的前提下）匹配尽可能少的字符，这匹配方式叫做懒惰匹配。<br>特性：从左到右，从字符串的最左边开始匹配，每次试图不读入字符匹配，匹配成功，则完成匹配，否则读入一个字符再匹配，依此循环（读入字符、匹配）直到匹配成功或者把字符串的字符匹配完为止。</p>
</blockquote>
<p>懒惰量词是在贪婪量词后面加个“？”</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx7t2lygj30h206mq3g.jpg" alt="img"><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx7r9n6wj30h206mq3g.jpg" alt="img"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   String reg=<span class="string">"(\\d&#123;1,2&#125;?)(\\d&#123;3,4&#125;)"</span>;        </span><br><span class="line"><span class="number">2</span>        String test=<span class="string">"61762828 176 2991 87321"</span>;</span><br><span class="line"><span class="number">3</span>        System.out.println(<span class="string">"文本："</span>+test);</span><br><span class="line"><span class="number">4</span>        System.out.println(<span class="string">"贪婪模式："</span>+reg);</span><br><span class="line"><span class="number">5</span>        Pattern p1 =Pattern.compile(reg);</span><br><span class="line"><span class="number">6</span>        Matcher m1 = p1.matcher(test);</span><br><span class="line"><span class="number">7</span>        <span class="keyword">while</span>(m1.find())&#123;</span><br><span class="line"><span class="number">8</span>            System.out.println(<span class="string">"匹配结果："</span>+m1.group(<span class="number">0</span>));</span><br><span class="line"><span class="number">9</span>        &#125;</span><br></pre></td></tr></table></figure>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>   文本：<span class="number">61762828</span> <span class="number">176</span> <span class="number">2991</span> <span class="number">87321</span></span><br><span class="line"><span class="number">2</span>   贪婪模式：(\d&#123;<span class="number">1</span>,<span class="number">2</span>&#125;?)(\d&#123;<span class="number">3</span>,<span class="number">4</span>&#125;)</span><br><span class="line"><span class="number">3</span>   匹配结果：<span class="number">61762</span></span><br><span class="line"><span class="number">4</span>   匹配结果：<span class="number">2991</span></span><br><span class="line"><span class="number">5</span>   匹配结果：<span class="number">87321</span></span><br></pre></td></tr></table></figure>
<p>解答：</p>
<blockquote>
<p>“61762” 是左边的懒惰匹配出6，右边的贪婪匹配出1762<br>“2991”  是左边的懒惰匹配出2，右边的贪婪匹配出991<br>“87321” 左边的懒惰匹配出8，右边的贪婪匹配出7321</p>
</blockquote>
<h3 id="5-反义"><a href="#5-反义" class="headerlink" title="5. 反义"></a><strong>5. 反义</strong></h3><p>前面说到元字符的都是要匹配什么什么，当然如果你想反着来，不想匹配某些字符，正则也提供了一些常用的反义元字符：</p>
<p><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx7e070dj30h307twf5.jpg" alt="img"><img src="https://tva1.sinaimg.cn/large/008eGmZEgy1gmrx7i6xktj30h307twf5.jpg" alt="img"></p>
<p>正则进阶知识就讲到这里，正则是一门博大精深的语言，其实学会它的一些语法和知识点还算不太难，但想要做到真正学以致用能写出非常6的正则，还有很远的距离，只有真正对它感兴趣的，并且经常研究和使用它，才会渐渐的理解它的博大精深之处，我就带你们走到这，剩下的，靠自己啦。</p>
<p>作者：老刘<br>链接：<span class="exturl" data-url="aHR0cHM6Ly93d3cuemhpaHUuY29tL3F1ZXN0aW9uLzQ4MjE5NDAxL2Fuc3dlci83NDI0NDQzMjY=" title="https://www.zhihu.com/question/48219401/answer/742444326">https://www.zhihu.com/question/48219401/answer/742444326<i class="fa fa-external-link"></i></span><br>来源：知乎<br>著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。</p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        
          
        
        <div class="post-tags">
          
            <a href="/tags/正则表达式/" rel="tag"><i class="fa fa-tag"></i> 正则表达式</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div class="social_share">
            
              <div>
                

<script src="//cdn.jsdelivr.net/npm/ilyabirman-likely@2/release/likely.js"></script>



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/ilyabirman-likely@2/release/likely.css">


  


<div class="likely likely-light">
	
 	 	<div class="twitter">Tweet</div>
	
 	 	<div class="facebook">Share</div>
	
 	 	<div class="linkedin">Link</div>
	
 	 	<div class="gplus">Plus</div>
	
 	 	<div class="vkontakte">Share</div>
	
 	 	<div class="odnoklassniki">Class</div>
	
 	 	<div class="telegram">Send</div>
	
 	 	<div class="whatsapp">Send</div>
	
 	 	<div class="pinterest">Pin</div>
	
</div>

              </div>
            
            
            
              <div>
                
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

              </div>
            
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/命令——网络工具中的瑞士军刀.html" rel="next" title="linux netcat 命令——网络工具中的瑞士军刀">
                <i class="fa fa-chevron-left"></i> linux netcat 命令——网络工具中的瑞士军刀
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019-Flink社区年度文章合集.html" rel="prev" title="2019_Flink社区年度文章合集">
                2019_Flink社区年度文章合集 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk3My82NTM4"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://hexoblog-1254111960.cos.ap-guangzhou.myqcloud.com/HexoBlog-tou.jpg" alt="Daniel X">
            
              <p class="site-author-name" itemprop="name">Daniel X</p>
              <div class="site-description motion-element" itemprop="description">專注于大数据技術，分享干货</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">125</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">15</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">63</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2R1ZGVmdQ==" title="GitHub &rarr; https://github.com/dudefu"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOmR1ZGVmdUBmb3htYWlsLmNvbT9zdWJqZWN0PUhlbGxvJTIwYWdhaW4=" title="E-mail &rarr; mailto:dudefu@foxmail.com?subject=Hello%20again"><i class="fa fa-fw fa-envelope"></i>E-mail</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly93ZWliby5jb20vZHVkZWZ1" title="Weibo &rarr; https://weibo.com/dudefu"><i class="fa fa-fw fa-weibo"></i>Weibo</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly93cGEucXEuY29tL21zZ3JkP3Y9MyZ1aW49MTU3NzU3MTk1OSZzaXRlPWR1ZGVmdS5pbmZvJm1lbnU9eWVz" title="QQ &rarr; https://wpa.qq.com/msgrd?v=3&uin=1577571959&site=dudefu.info&menu=yes"><i class="fa fa-fw fa-qq"></i>QQ</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#正则基础知识点："><span class="nav-number">1.</span> <span class="nav-text">正则基础知识点：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-元字符"><span class="nav-number">1.1.</span> <span class="nav-text">1.元字符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-重复限定符"><span class="nav-number">1.2.</span> <span class="nav-text">2. 重复限定符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-分组"><span class="nav-number">1.3.</span> <span class="nav-text">3. 分组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-转义"><span class="nav-number">1.4.</span> <span class="nav-text">4. 转义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-条件或"><span class="nav-number">1.5.</span> <span class="nav-text">5. 条件或</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-区间"><span class="nav-number">1.6.</span> <span class="nav-text">6. 区间</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#正则进阶知识点："><span class="nav-number">2.</span> <span class="nav-text">正则进阶知识点：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-零宽断言"><span class="nav-number">2.1.</span> <span class="nav-text">1. 零宽断言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-捕获和非捕获"><span class="nav-number">2.2.</span> <span class="nav-text">2. 捕获和非捕获</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-反向引用"><span class="nav-number">2.3.</span> <span class="nav-text">3. 反向引用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-贪婪和非贪婪"><span class="nav-number">2.4.</span> <span class="nav-text">4. 贪婪和非贪婪</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-反义"><span class="nav-number">2.5.</span> <span class="nav-text">5. 反义</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">粤ICP备18110871号 </span>&copy; 2017 – <span itemprop="copyrightYear">2021</span>
  <span class="with-love" id="animate">
    <i class="fa fa-spinner"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">dudefu</span>

  

  
</div>

<!--

  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Pisces</span> v7.1.2</div>

-->



        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  
    
    
      
    
  
  <script color="26,26,26" opacity="0.5" zindex="-1" count="99" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1/canvas-nest.min.js"></script>









  
  
  <script id="ribbon" size="300" alpha="0.6" zindex="-1" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>



  



  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script src="/lib/reading_progress/reading_progress.js"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  
  <script src="/js/js.cookie.js?v=7.1.2"></script>
  <script src="/js/scroll-cookie.js?v=7.1.2"></script>


  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: true,
    notify: true,
    appId: '1N5rpk874DGudJw2wCL9J011-gzGzoHsz',
    appKey: '9Y83e6suJgx567wtxhKy45IN',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: true,
    lang: 'zk-cn' || 'zh-cn'
  });
</script>




  
    <script>
  window.livereOptions = {
    refer: '正则表达式学习.html'
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
</script>

  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase.js"></script>
  <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase-firestore.js"></script>
  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.1/bluebird.core.min.js"></script>
  
  <script>
    (function () {

      firebase.initializeApp({
        apiKey: '',
        projectId: ''
      })

      function getCount(doc, increaseCount) {
        //increaseCount will be false when not in article page

        return doc.get().then(function (d) {
          var count
          if (!d.exists) { //has no data, initialize count
            if (increaseCount) {
              doc.set({
                count: 1
              })
              count = 1
            }
            else {
              count = 0
            }
          }
          else { //has data
            count = d.data().count
            if (increaseCount) {
              if (!(window.localStorage && window.localStorage.getItem(title))) { //if first view this article
                doc.set({ //increase count
                  count: count + 1
                })
                count++
              }
            }
          }
          if (window.localStorage && increaseCount) { //mark as visited
            localStorage.setItem(title, true)
          }

          return count
        })
      }

      function appendCountTo(el) {
        return function (count) {
          $(el).append(
            $('<span>').addClass('post-visitors-count').append(
              $('<span>').addClass('post-meta-divider').text('|')
            ).append(
              $('<span>').addClass('post-meta-item-icon').append(
                $('<i>').addClass('fa fa-users')
              )
              ).append($('<span>').text('阅读次数 ' + count))
          )
        }
      }

      var db = firebase.firestore()
      var articles = db.collection('articles')

      //https://hexo.io/docs/variables.html
      var isPost = '正则表达式学习'.length > 0
      var isArchive = '' === 'true'
      var isCategory = ''.length > 0
      var isTag = ''.length > 0

      if (isPost) { //is article page
        var title = '正则表达式学习'
        var doc = articles.doc(title)

        getCount(doc, true).then(appendCountTo($('.post-meta')))
      }
      else if (!isArchive && !isCategory && !isTag) { //is index page
        var titles = [] //array to titles

        var postsstr = '' //if you have a better way to get titles of posts, please change it
        eval(postsstr)

        var promises = titles.map(function (title) {
          return articles.doc(title)
        }).map(function (doc) {
          return getCount(doc)
        })
        Promise.all(promises).then(function (counts) {
          var metas = $('.post-meta')
          counts.forEach(function (val, idx) {
            appendCountTo(metas[idx])(val)
          })
        })
      }
    })()
  </script>


  
  

  
  

  


  
<script>
if ($('body').find('div.pdf').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/pdfobject@2/pdfobject.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      $('body').find('div.pdf').each(function(i, o) {
        PDFObject.embed($(o).attr('target'), $(o), {
          pdfOpenParams: {
            navpanes: 0,
            toolbar: 0,
            statusbar: 0,
            pagemode: 'thumbs',
            view: 'FitH'
          },
          PDFJS_URL: '/lib/pdf/web/viewer.html',
          height: $(o).attr('height') || '500px'
        });
      });
    },
  });
}
</script>


  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'dark',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  
  
  
  <script src="/lib/bookmark/bookmark.min.js?v=1.0"></script>
  <script>
  
    bookmark.scrollToMark('auto', "#更多");
  
  </script>


  
<script>
  $('.highlight').not('.gist .highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      const selection = document.getSelection();
      const selected = selection.rangeCount > 0 ? selection.getRangeAt(0) : false;
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
      if (selected) {
        selection.removeAllRanges();
        selection.addRange(selected);
      }
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
